package de.tum.in.eist.poll.client.control;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.BarChart;

import de.tum.in.eist.poll.client.gui.Dashboard;
import de.tum.in.eist.poll.client.gui.LoginPanel;
import de.tum.in.eist.poll.shared.User;
import de.tum.in.eist.poll.shared.service.PollService;
import de.tum.in.eist.poll.shared.service.PollServiceAsync;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EIST_POLL implements EntryPoint {

	public static final PollServiceAsync pollSvc = GWT
			.create(PollService.class);
	private User user = null;
	private LoginPanel loginPanel;
	private Dashboard dashboard;

	private static boolean isChartAPILoaded = false;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		if (Cookies.getCookie("EIST_POLL_SESSIONID") != null) {
			System.out.println("trying to restore session...");
			pollSvc.login(Cookies.getCookie("EIST_POLL_SESSIONID"),
					new AsyncCallback<User>() {

						@Override
						public void onSuccess(User result) {
							EIST_POLL.this.user = result;
							onAPIsLoad();
						}

						@Override
						public void onFailure(Throwable caught) {
							onAPIsLoad();
						}
					});
		} else {
			onAPIsLoad();
		}
	}

	private void onAPIsLoad() {
		System.out.println("loading chart API...");
		Runnable visrun = new Runnable() {
			@Override
			public void run() {
				isChartAPILoaded = true;
				if (user != null)
					loadDashboard();
				else
					loadLoginForm();
			}
		};
		VisualizationUtils.loadVisualizationApi(visrun, BarChart.PACKAGE);
	}

	protected void loadLoginForm() {
		RootPanel.get().clear();
		loginPanel = new LoginPanel();
		new LoginHandler(this, loginPanel);
		RootPanel.get().add(loginPanel);
	}

	public static boolean isChartAPIloaded() {
		return isChartAPILoaded;
	}

	protected void loadDashboard() {
		dashboard = new Dashboard(this);
		RootPanel.get().clear();
		RootPanel.get().add(dashboard);
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getUser() {
		return user;
	}

	public Dashboard getDashboard() {
		return dashboard;
	}
}
